// ------------------------------------------------------------------------------------------
// Licensed by Interprise Solutions.
// http://www.InterpriseSolutions.com
// For details on this license please visit  the product homepage at the URL above.
// THE ABOVE NOTICE MUST REMAIN INTACT.
// ------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.IO;
using System.Xml;
using System.Configuration;
using System.Web.Security;

namespace InterpriseSuiteEcommerceCommon.Integration.Interprise.Admin
{
    public class AuthorizationHandler : IHttpHandler
    {
        #region IHttpHandler Members

        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            HttpContext ctx = context;

            // other modules should handle the presence of this file
            FileInfo resourceInfo = new FileInfo(ctx.Request.PhysicalPath);
            if (resourceInfo.Exists)
            {
                if (AuthorizationModuleConfiguration.Instance.ProtectedDirectories.ContainsKey(resourceInfo.Directory.FullName))
                {
                    ProtectedDirectory dir = AuthorizationModuleConfiguration.Instance.ProtectedDirectories[resourceInfo.Directory.FullName];
                    if (dir != null)
                    {
                        // the directory is protected
                        if (!ctx.Request.IsAuthenticated)
                        {
                            if (!string.IsNullOrEmpty(dir.LoginUrl))
                            {
                                bool isRequestedFileSameAsLogin =
                                ctx.Server.MapPath(dir.LoginUrl).Equals(ctx.Server.MapPath(ctx.Request.Url.LocalPath), StringComparison.InvariantCultureIgnoreCase);

                                if (!isRequestedFileSameAsLogin)
                                {
                                    ctx.RewritePath(dir.LoginUrl);
                                }
                            }
                            else
                            {
                                // throw an invalid access error
                                ctx.Response.StatusCode = 403;
                                ctx.Response.SuppressContent = true;
                                ctx.Response.End();
                            }
                        }
                    }
                }
            }
            
        }

        #endregion
    }
}
